import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../index.dart';
import 'toast_notifications.dart';

/// 关注用户选择对话框
class VamosFollowUserDialog extends StatelessWidget {
  const VamosFollowUserDialog({super.key});

  @override
  Widget build(BuildContext context) {
    // 直接通过service locator获取状态
    final state = appStore.state;
    final currentUser = state.userState.activeUser;
    if (currentUser == null) return const SizedBox.shrink();

    final followingList = followManager.getFollowingList(currentUser.uniqueId);
    final allUsers = state.userState.userCollection;

    // 获取关注用户的详细信息
    final followingUsers =
        allUsers
            .where((user) => followingList.contains(user.uniqueId))
            .toList();

    return Dialog(
      backgroundColor: Colors.transparent,
      child: Container(
        width: 320.w,
        constraints: BoxConstraints(maxHeight: 500.h),
        padding: 6.h.paddingBottom(),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 20,
              offset: const Offset(0, 10),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 标题栏
            Container(
              padding: 20.paddingAll(),
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(16.r),
                  topRight: Radius.circular(16.r),
                ),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      'Select Contact',
                      style: GoogleFonts.inter(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.black87,
                      ),
                    ),
                  ),
                  Icon(
                    Icons.close,
                    size: 20.w,
                    color: Colors.grey[600],
                  ).inkWell(onTap: () => Navigator.of(context).pop()),
                ],
              ),
            ),

            // 用户列表
            if (followingUsers.isEmpty)
              Container(
                padding: 40.paddingAll(),
                child: Column(
                  children: [
                    Icon(
                      Icons.person_add_disabled,
                      size: 48.w,
                      color: Colors.grey[400],
                    ).paddingBottom(16.h),
                    Text(
                      'No Following Users',
                      style: GoogleFonts.inter(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w500,
                        color: Colors.grey[600],
                      ),
                    ).paddingBottom(8.h),
                    Text(
                      'Follow some users to start chatting',
                      style: GoogleFonts.inter(
                        fontSize: 14.sp,
                        color: Colors.grey[500],
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
              )
            else
              Flexible(
                child: ListView.builder(
                  shrinkWrap: true,
                  padding: 8.paddingAll(),
                  itemCount: followingUsers.length,
                  itemBuilder: (context, index) {
                    final user = followingUsers[index];
                    return _buildUserItem(context, user, currentUser);
                  },
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildUserItem(
    BuildContext context,
    UserDataEntity user,
    UserDataEntity currentUser,
  ) {
    return Container(
      margin: EdgeInsets.only(bottom: 8.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: Colors.grey[200]!, width: 1),
      ),
      child: ListTile(
        contentPadding: 12.paddingAll(),
        leading: Container(
          width: 40.w,
          height: 40.w,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8.r),
            image: DecorationImage(
              image: AssetImage(user.profileImage),
              fit: BoxFit.cover,
            ),
          ),
        ),
        title: Text(
          user.displayName,
          style: GoogleFonts.inter(
            fontSize: 16.sp,
            fontWeight: FontWeight.w500,
            color: Colors.black87,
          ),
        ),
        subtitle: Text(
          user.personalBio,
          style: GoogleFonts.inter(fontSize: 12.sp, color: Colors.grey[600]),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        trailing: Image.asset(
          'assets/images/chat.png',
          width: 20.w,
          height: 20.w,
          color: Colors.blue,
        ),
        onTap: () => _handleUserSelection(context, user, currentUser),
      ),
    );
  }

  void _handleUserSelection(
    BuildContext context,
    UserDataEntity selectedUser,
    UserDataEntity currentUser,
  ) async {
    // 关闭对话框
    Navigator.of(context).pop();

    // 检查是否已有对话
    final existingConversation = _findExistingConversation(
      currentUser.uniqueId,
      selectedUser.uniqueId,
    );

    if (existingConversation != null) {
      // 已有对话，直接跳转
      _navigateToConversation(context, existingConversation);
    } else {
      // 创建新对话
      await _createNewConversation(context, currentUser, selectedUser);
    }
  }

  ChatConversationEntity? _findExistingConversation(
    String currentUserId,
    String targetUserId,
  ) {
    final allConversations = chatManager.getAllConversations();

    try {
      return allConversations.firstWhere(
        (conversation) => conversation.participantId == targetUserId,
      );
    } catch (e) {
      return null;
    }
  }

  Future<void> _createNewConversation(
    BuildContext context,
    UserDataEntity currentUser,
    UserDataEntity targetUser,
  ) async {
    try {
      // 创建新对话
      final newConversation = ChatConversationEntity(
        conversationId: 'conv_${DateTime.now().millisecondsSinceEpoch}',
        participantId: targetUser.uniqueId,
        participantName: targetUser.displayName,
        participantAvatar: targetUser.profileImage,
        messageList: [],
        lastMessageContent: '',
        lastMessageType: ChatMessageType.textMessage,
        lastMessageTime: DateTime.now(),
      );

      // 保存对话
      final success = await chatManager.createNewConversation(newConversation);

      if (success) {
        // 跳转到新对话
        _navigateToConversation(context, newConversation);
      } else {
        // 显示错误提示
        ToastNotificationHelper.showErrorToast(
          context,
          message: 'Failed to create conversation',
        );
      }
    } catch (e) {
      ToastNotificationHelper.showErrorToast(
        context,
        message: 'Error creating conversation',
      );
    }
  }

  void _navigateToConversation(
    BuildContext context,
    ChatConversationEntity conversation,
  ) {
    // 设置活动对话，chat页面会自动监听并更新UI
    chatManager.setActiveConversation(conversation.conversationId);
  }
}

/// 显示关注用户选择对话框
void showVamosFollowUserDialog(BuildContext context) {
  showDialog(
    context: context,
    barrierDismissible: true,
    builder: (context) => const VamosFollowUserDialog(),
  );
}
